package concurrent;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ForkJoinSumExample {

    // 任务类，继承 RecursiveTask
    static class SumTask extends RecursiveTask<Long> {
        private static final int THRESHOLD = 10; // 阈值，小于这个直接计算
        private int[] arr;
        private int start, end;

        public SumTask(int[] arr, int start, int end) {
            this.arr = arr;
            this.start = start;
            this.end = end;
        }

        @Override
        protected Long compute() {
            if (end - start <= THRESHOLD) { // 小任务，直接计算
                long sum = 0;
                for (int i = start; i < end; i++) {
                    sum += arr[i];
                }
                return sum;
            } else { // 大任务，继续拆分
                int middle = (start + end) / 2;
                SumTask leftTask = new SumTask(arr, start, middle);
                SumTask rightTask = new SumTask(arr, middle, end);

                leftTask.fork(); // 异步执行左任务
                rightTask.fork(); // 异步执行右任务

                long leftResult = leftTask.join(); // 等待左任务结果
                long rightResult = rightTask.join(); // 等待右任务结果

                return leftResult + rightResult;
            }
        }
    }

    public static void main(String[] args) {
        // 准备数据
        int[] arr = new int[100];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i + 1;
        }

        // 创建任务
        SumTask task = new SumTask(arr, 0, arr.length);

        // 创建 ForkJoinPool
        ForkJoinPool pool = new ForkJoinPool();

        // 执行任务
        Long result = pool.invoke(task);

        System.out.println("数组元素和 = " + result);
    }
}